"""
智能MCP系统使用示例
展示完整的端到端运维处理流程
"""

import sys
import os
import logging
from datetime import datetime
import asyncio

# 支持包内直接运行
if __name__ == "__main__" and __package__ is None:
    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    __package__ = "agent_mcp"

from agent_mcp.features.intelligent_decision_engine import IntelligentDecisionEngine
from agent_mcp.features.ansible_script_generator import AnsibleScriptGenerator

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def run_test_case(llm_data, case_name):
    logger.info(f"\n=== 测试用例: {case_name} ===")
    engine = IntelligentDecisionEngine()
    try:
        plan = await engine.process_llm_inference(llm_data)
        logger.info(f"生成执行计划: {plan}")
        result = await engine.execute_plan(plan)
        logger.info(f"执行结果: {result}")
        # 新增：自动生成playbook脚本
        agent_results = []
        if isinstance(result, dict) and "task_results" in result:
            for task_id, task_info in result["task_results"].items():
                agent_results.append({
                    "agent_type": task_info.get("agent_type", "unknown"),
                    "result": task_info.get("result", {}),
                    "parameters": task_info.get("result", {}).get("parameters", {})
                })
        if agent_results:
            script_gen = AnsibleScriptGenerator()
            playbook = script_gen.generate_playbook_from_agent_results(agent_results)
            playbook_path = script_gen.save_playbook(playbook)
            logger.info(f"已自动生成Playbook: {playbook_path}")
        else:
            logger.warning("未能提取到有效的agent_results，未生成playbook")
    except Exception as e:
        logger.error(f"❌ 测试用例失败: {e}")

if __name__ == "__main__":
    test_cases = [
        ({
            "problem_type": "network_connectivity",
            "severity": 5,
            "description": "network_congestion",
            "parameters": {},
            "affected_services": ["network", "database", "external_services"],
            "suggested_actions": ["检查网络设备状态", "优化网络路由"],
            "confidence": 0.85,
            "reasoning": "service_availability",
            "timestamp": "2025-07-14T12:05:21"
        }, "自定义网络连通性测试")
    ]

    loop = asyncio.get_event_loop()
    for llm_data, case_name in test_cases:
        loop.run_until_complete(run_test_case(llm_data, case_name)) 